// releasePage/pages/addProjectTeam/addProjectTeam.js
import throttle from '../../../utils/throttle.js';
import { hasPermission } from '../../../utils/tools';
const app = getApp();

Page({
    /**
     * 页面的初始数据
     */
    data: {
        projectTeamName: '',
        // 是否有组员
        hasMember: false,
        projectTeamMembers: [
            {
                title: '交付组长',
                realname: '',
                uid: '',
                backup: '',
                backupid: '',
            },
            {
                title: '组员1',
                realname: '',
                uid: '',
                backup: '',
                backupid: '',
            },
            {
                title: '组员2',
                realname: '',
                uid: '',
                backup: '',
                backupid: '',
            },
        ],
        // 长按的条目索引
        longpressIndex: null,
        // logo
        src: '',
        // 项目组id
        id: '',
        // 控制添加备注的弹框
        show: false,
        // 当前备注
        currentMark: '',
        // 组长相关的东西只能管理员以上才能改
        projectauthority: '',
    },

    onLoad(option) {
        if (option.id) {
            // 有id表示是再次编辑
            // 设置页面顶部title
            wx.setNavigationBarTitle({
                title: '编辑项目组',
            });
            this.getProjectTeamDetail(option.id);
            this.setData({
                id: option.id,
            });
        }
    },

    upload() {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
            success(res) {
                const src = res.tempFilePaths[0];
                wx.navigateTo({
                    url: `../cropper/cropper?src=${src}`,
                });
            },
        });
    },

    handleLongpress(e) {
        let { index } = e.currentTarget.dataset;
        // 1.如果没有值就不弹出删除 2.组长不能改自己
        if (
            (index < 3 && !this.data.projectTeamMembers[index].uid) ||
            (index === 0 &&
                !hasPermission(['00', '01']) &&
                this.data.projectauthority == '02')
        )
            return;
        this.setData({
            longpressIndex: index,
        });
    },

    clearDeleteBtn() {
        this.setData({
            longpressIndex: null,
        });
    },

    // 删除成员，前三个只能删除内容，不删除整个条目
    deleteMember(e) {
        let _that = this;
        wx.showModal({
            title: '提示',
            content: '确认删除吗？',
            success: function (res) {
                if (res.confirm) {
                    if (_that.data.longpressIndex > 2) {
                        _that.data.projectTeamMembers.splice(
                            _that.data.longpressIndex,
                            1
                        );
                    } else {
                        _that.data.projectTeamMembers[
                            _that.data.longpressIndex
                        ].uid = '';
                        _that.data.projectTeamMembers[
                            _that.data.longpressIndex
                        ].realname = '';
                        _that.data.projectTeamMembers[
                            _that.data.longpressIndex
                        ].backup = '';
                        _that.data.projectTeamMembers[
                            _that.data.longpressIndex
                        ].backupid = '';
                    }
                    _that.setData({
                        projectTeamMembers: _that.data.projectTeamMembers,
                        longpressIndex: null,
                    });
                } else {
                    console.log('点击取消回调');
                }
            },
        });
    },

    // 添加备注
    addMark(e) {
        if (typeof this.data.longpressIndex === 'number') {
            this.setData({
                currentMark:
                    this.data.projectTeamMembers[this.data.longpressIndex]
                        .backup || '',
            });
        }
        this.setData({
            show: true,
        });
    },

    inputMark(e) {
        this.setData({
            currentMark: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 6);
    },

    // 关闭添加备注弹框
    onCancel() {
        this.setData({
            show: false,
            longpressIndex: null,
        });
    },

    // 点击弹框确认按钮
    onConfirm() {
        let _that = this;
        _that.data.projectTeamMembers[_that.data.longpressIndex].backup =
            _that.data.currentMark;
        _that.setData({
            projectTeamMembers: _that.data.projectTeamMembers,
            longpressIndex: null,
        });
    },

    bindKeyInput(e) {
        this.setData({
            projectTeamName: e.detail.value,
        });
        app.numLimitTip(e.detail.value.length, 6);
    },

    changeNav: throttle(
        function (e) {
            let { index } = e.currentTarget.dataset;
            if (typeof index == 'number') {
                if (
                    index === 0 &&
                    !hasPermission(['00', '01']) &&
                    this.data.projectauthority == '02'
                ) {
                    wx.showToast({
                        title: '暂无权限',
                        icon: 'none',
                        duration: 2000,
                    });
                } else {
                    let nav = e.currentTarget.dataset.nav;
                    console.log(nav);
                    wx.navigateTo({
                        url: nav,
                    });
                }
            } else {
                let nav = e.currentTarget.dataset.nav;
                console.log(nav);
                wx.navigateTo({
                    url: nav,
                });
            }
        },
        200,
        {
            trailing: false,
        }
    ),

    // 获取项目组详情
    getProjectTeamDetail(id) {
        let _that = this;
        wx.request({
            url: app.globalData.rootPath + 'cjMap/getProjectTeamDetail',
            data: {
                authId: app.globalData.authId,
                id: id,
            },
            success(res) {
                if (res.data.status === '0') {
                    let tempProjectTeamMembers = [];
                    tempProjectTeamMembers.push({
                        title: '交付组长',
                        realname: res.data.leader[0].realname,
                        uid: res.data.leader[0].uid,
                        backup: res.data.leader[0].backup || '',
                        backupid: res.data.leader[0].backupid || '',
                    });
                    if (res.data.member) {
                        res.data.member.map((member, index) => {
                            tempProjectTeamMembers.push({
                                title: `组员${index + 1}`,
                                realname: member.realname,
                                uid: member.uid,
                                backup: member.backup || '',
                                backupid: member.backupid || '',
                            });
                        });
                    }
                    // 如果没有组员，需要补两个空组员
                    // 如果只有一个组员，需要补一个空组员
                    if (tempProjectTeamMembers.length === 1) {
                        tempProjectTeamMembers.push(
                            {
                                title: '组员1',
                                realname: '',
                                uid: '',
                                backup: '',
                                backupid: '',
                            },
                            {
                                title: '组员2',
                                realname: '',
                                uid: '',
                                backup: '',
                                backupid: '',
                            }
                        );
                    } else if (tempProjectTeamMembers.length === 2) {
                        tempProjectTeamMembers.push({
                            title: '组员2',
                            realname: '',
                            uid: '',
                            backup: '',
                            backupid: '',
                        });
                    }

                    _that.setData({
                        projectTeamName: res.data.projectTeam.pjteamname,
                        src: res.data.projectTeam.pjteamlogopicurl,
                        projectTeamMembers: tempProjectTeamMembers,
                        projectauthority: res.data.projectauthority || '',
                    });
                }
            },
        });
    },

    // 提交项目组
    submit: throttle(
        function () {
            let _that = this;
            if (app.visitorPublish()) return; //游客发布限制
            if (
                _that.data.src &&
                _that.data.projectTeamName &&
                _that.data.projectTeamMembers[0].uid
            ) {
                // 获取组员id数组
                let memberIdArr = [];
                // 获取组员备注数组
                let memberBackupArr = [];
                // 获取组员备注id
                let memberBackupIdArr = [];
                for (let i = 1; i < _that.data.projectTeamMembers.length; i++) {
                    // 防止有的组员为空，又添加新组员
                    if (_that.data.projectTeamMembers[i].uid) {
                        memberIdArr.push(_that.data.projectTeamMembers[i].uid);
                        memberBackupArr.push(
                            _that.data.projectTeamMembers[i].backup || ''
                        );
                        memberBackupIdArr.push(
                            _that.data.projectTeamMembers[i].backupid || ''
                        );
                    }
                }

                if (_that.data.id) {
                    console.log('编辑');
                    wx.request({
                        method: 'POST',
                        url:
                            app.globalData.rootPath +
                            'cjMap/editProjectTeam?authId=' +
                            app.globalData.authId,
                        data: {
                            delflg: '00',
                            pjteamlogopicurl: _that.data.src,
                            pjteamname: _that.data.projectTeamName,
                            leaderid: _that.data.projectTeamMembers[0].uid,
                            memberid: memberIdArr.join(','),
                            id: _that.data.id,
                            leaderbackup:
                                _that.data.projectTeamMembers[0].backup,
                            memberbackup: memberBackupArr.join(','),
                            memberbackupid: memberBackupIdArr.join(','),
                            leaderbackupid:
                                _that.data.projectTeamMembers[0].backupid,
                        },
                        success(res) {
                            if (res.data.status === '0') {
                                wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 1500,
                                });
                                let pages = getCurrentPages(); //当前页面栈
                                let prevPage = pages[pages.length - 2]; //上一页面（项目组详情页面）
                                prevPage.refresh();

                                let prev2Page = pages[pages.length - 3]; //上上一页面（项目组页面）
                                prev2Page.getProjectTeamDetail(_that.data.id);

                                let prev3Page = pages[pages.length - 4]; //上上上一页面（通告页面）
                                prev3Page.getProjectTeamList();
                                setTimeout(() => {
                                    wx.navigateBack({
                                        detal: 1,
                                    });
                                }, 1500);
                            }
                        },
                    });
                } else {
                    wx.request({
                        method: 'POST',
                        url:
                            app.globalData.rootPath +
                            'cjMap/createProjectTeam?authId=' +
                            app.globalData.authId,
                        data: {
                            delflg: '00',
                            pjteamlogopicurl: _that.data.src,
                            pjteamname: _that.data.projectTeamName,
                            leaderid: _that.data.projectTeamMembers[0].uid,
                            memberid: memberIdArr.join(','),
                            leaderbackup:
                                _that.data.projectTeamMembers[0].backup,
                            memberbackup: memberBackupArr.join(','),
                        },
                        success(res) {
                            console.log(res);
                            if (res.data.status === '0') {
                                wx.showToast({
                                    title: '保存成功',
                                    icon: 'success',
                                    duration: 1500,
                                });
                                let pages = getCurrentPages(); //当前页面栈
                                let prevPage = pages[pages.length - 2]; //上一页面
                                prevPage.getProjectTeamList();
                                setTimeout(() => {
                                    wx.navigateBack({
                                        detal: 1,
                                    });
                                }, 1500);
                            }
                        },
                    });
                }
            }
        },
        10000,
        {
            trailing: false,
        }
    ),
});
